<template>
  <div class="user-edit">
    <h1>编辑用户</h1>
    
    <el-form :model="form" label-width="100px" @submit.prevent="handleSubmit">
      <el-form-item label="用户ID">
        <el-input v-model="form.id" disabled></el-input>
      </el-form-item>
      
      <el-form-item label="用户名">
        <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      
      <el-form-item label="邮箱">
        <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      
      <el-form-item label="角色">
        <el-select v-model="form.roleId" placeholder="请选择角色">
          <el-option label="管理员" value="1"></el-option>
          <el-option label="教师" value="2"></el-option>
          <el-option label="学生" value="3"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import AdminAPI from '@/api/admin'

export default {
  name: 'UserEdit',
  data() {
    return {
      form: {
        id: '',
        username: '',
        password: '',
        email: '',
        roleId: 3 // 默认为学生
      }
    }
  },
  created() {
    // 如果有路由参数，加载用户信息
    const userId = this.$route.params.id
    if (userId) {
      this.loadUserInfo(userId)
    }
  },
  methods: {
    // 加载用户信息
    async loadUserInfo(userId) {
      try {
        const res = await AdminAPI.getUserInfo(userId)
        if (res.data.code === 200 && res.data.msg === 'success') {
          this.form = { ...res.data.data }
        } else {
          this.$message.error('获取用户信息失败')
        }
      } catch (error) {
        this.$message.error('获取用户信息失败: ' + error.message)
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        const res = await AdminAPI.updateUser(this.form)
        if (res.data.code === 200 && res.data.msg === 'success') {
          this.$message.success('用户更新成功')
          // 返回用户列表页面
          this.$router.push('/admin/users')
        } else {
          this.$message.error('用户更新失败: ' + res.data.data)
        }
      } catch (error) {
        this.$message.error('用户更新失败: ' + error.message)
      }
    },

    // 取消操作
    handleCancel() {
      this.$router.push('/admin/users')
    }
  }
}
</script>

<style scoped>
.user-edit {
  padding: 20px;
}

</style>